// src/pages/add/add.js
import { billAPI, categoryAPI } from '../../utils/api.js'
import { formatAmount, getCurrentDate, getCurrentTime, validateAmount, showError, showSuccess } from '../../utils/util.js'
import { categoryStorage, draftStorage } from '../../utils/storage.js'

Page({
  data: {
    // 账单类型
    billType: 'expense', // expense | income
    
    // 表单数据
    formData: {
      amount: '',
      category: '',
      categoryId: '',
      date: '',
      time: '',
      note: ''
    },
    
    // 分类数据
    categories: [],
    expenseCategories: [],
    incomeCategories: [],
    
    // UI状态
    showKeyboard: false,
    showCategoryPicker: false,
    showDatePicker: false,
    showTimePicker: false,
    
    // 键盘输入
    keyboardValue: '0',
    
    // 加载状态
    loading: false,
    submitting: false
  },

  onLoad(options) {
    // 从参数获取账单类型
    if (options.type && ['income', 'expense'].includes(options.type)) {
      this.setData({ billType: options.type })
    }
    
    this.initPage()
  },

  onShow() {
    // 检查是否有草稿
    this.loadDraft()
  },

  onHide() {
    // 保存草稿
    this.saveDraft()
  },

  onUnload() {
    // 页面卸载时保存草稿
    this.saveDraft()
  },

  /**
   * 初始化页面
   */
  async initPage() {
    try {
      this.setData({
        'formData.date': getCurrentDate(),
        'formData.time': getCurrentTime()
      })

      await this.loadCategories()
    } catch (error) {
      console.error('页面初始化失败:', error)
      showError('页面加载失败')
    }
  },

  /**
   * 加载分类数据
   */
  async loadCategories() {
    try {
      // 先从缓存获取
      let categories = categoryStorage.getCategories()
      
      if (categories.length === 0) {
        // 缓存为空，从服务器获取
        const result = await categoryAPI.getCategories()
        if (result.success) {
          categories = result.data.categories
          categoryStorage.setCategories(categories)
        }
      }

      const expenseCategories = categories.filter(cat => cat.type === 'expense')
      const incomeCategories = categories.filter(cat => cat.type === 'income')

      this.setData({
        categories,
        expenseCategories,
        incomeCategories
      })
    } catch (error) {
      console.error('加载分类失败:', error)
    }
  },

  /**
   * 加载草稿
   */
  loadDraft() {
    const draft = draftStorage.getDraftBill()
    if (draft && Object.keys(draft).length > 0) {
      this.setData({
        formData: { ...this.data.formData, ...draft },
        keyboardValue: draft.amount ? draft.amount.toString() : '0'
      })
    }
  },

  /**
   * 保存草稿
   */
  saveDraft() {
    const { formData, keyboardValue } = this.data
    if (keyboardValue !== '0' || formData.category || formData.note) {
      const draft = {
        ...formData,
        amount: parseFloat(keyboardValue) || 0
      }
      draftStorage.setDraftBill(draft)
    }
  },

  /**
   * 切换账单类型
   */
  onTypeTap(e) {
    const { type } = e.currentTarget.dataset
    this.setData({ 
      billType: type,
      'formData.category': '',
      'formData.categoryId': ''
    })
  },

  /**
   * 显示金额键盘
   */
  onAmountTap() {
    this.setData({ showKeyboard: true })
  },

  /**
   * 键盘输入
   */
  onKeyboardInput(e) {
    const { key } = e.currentTarget.dataset
    let { keyboardValue } = this.data

    if (key === 'delete') {
      // 删除
      if (keyboardValue.length > 1) {
        keyboardValue = keyboardValue.slice(0, -1)
      } else {
        keyboardValue = '0'
      }
    } else if (key === 'clear') {
      // 清空
      keyboardValue = '0'
    } else if (key === '.') {
      // 小数点
      if (keyboardValue.indexOf('.') === -1) {
        keyboardValue += '.'
      }
    } else {
      // 数字
      if (keyboardValue === '0') {
        keyboardValue = key
      } else {
        // 限制小数位数
        const parts = keyboardValue.split('.')
        if (parts.length === 2 && parts[1].length >= 2) {
          return
        }
        keyboardValue += key
      }
    }

    // 限制最大金额
    const amount = parseFloat(keyboardValue)
    if (amount > 999999.99) {
      return
    }

    this.setData({ keyboardValue })
  },

  /**
   * 隐藏键盘
   */
  onKeyboardHide() {
    this.setData({ showKeyboard: false })
  },

  /**
   * 显示分类选择器
   */
  onCategoryTap() {
    this.setData({ showCategoryPicker: true })
  },

  /**
   * 选择分类
   */
  onCategorySelect(e) {
    const { category } = e.detail
    this.setData({
      'formData.category': category.name,
      'formData.categoryId': category._id,
      showCategoryPicker: false
    })
  },

  /**
   * 隐藏分类选择器
   */
  onCategoryPickerHide() {
    this.setData({ showCategoryPicker: false })
  },

  /**
   * 显示日期选择器
   */
  onDateTap() {
    this.setData({ showDatePicker: true })
  },

  /**
   * 日期选择
   */
  onDateChange(e) {
    this.setData({
      'formData.date': e.detail.value,
      showDatePicker: false
    })
  },

  /**
   * 显示时间选择器
   */
  onTimeTap() {
    this.setData({ showTimePicker: true })
  },

  /**
   * 时间选择
   */
  onTimeChange(e) {
    this.setData({
      'formData.time': e.detail.value,
      showTimePicker: false
    })
  },

  /**
   * 备注输入
   */
  onNoteInput(e) {
    this.setData({
      'formData.note': e.detail.value
    })
  },

  /**
   * 提交表单
   */
  async onSubmit() {
    if (this.data.submitting) return

    try {
      // 表单验证
      const validation = this.validateForm()
      if (!validation.valid) {
        showError(validation.message)
        return
      }

      this.setData({ submitting: true })

      const { billType, formData, keyboardValue } = this.data
      const amount = parseFloat(keyboardValue)

      const billData = {
        type: billType,
        amount: amount,
        category: formData.category,
        categoryId: formData.categoryId,
        date: formData.date,
        time: formData.time,
        note: formData.note.trim()
      }

      const result = await billAPI.addBill(billData)

      if (result.success) {
        showSuccess('记账成功')
        
        // 清除草稿
        draftStorage.clearDraftBill()
        
        // 显示预算提醒
        if (result.data.budgetWarning) {
          setTimeout(() => {
            wx.showModal({
              title: '预算提醒',
              content: result.data.budgetWarning.message,
              showCancel: false
            })
          }, 1000)
        }

        // 返回上一页或跳转到首页
        const pages = getCurrentPages()
        if (pages.length > 1) {
          wx.navigateBack()
        } else {
          wx.switchTab({ url: '/src/pages/home/home' })
        }
      }
    } catch (error) {
      console.error('提交失败:', error)
      showError(error.message || '记账失败')
    } finally {
      this.setData({ submitting: false })
    }
  },

  /**
   * 表单验证
   */
  validateForm() {
    const { keyboardValue, formData } = this.data
    const amount = parseFloat(keyboardValue)

    if (!validateAmount(amount)) {
      return { valid: false, message: '请输入有效的金额' }
    }

    if (!formData.category) {
      return { valid: false, message: '请选择分类' }
    }

    if (!formData.date) {
      return { valid: false, message: '请选择日期' }
    }

    if (!formData.time) {
      return { valid: false, message: '请选择时间' }
    }

    return { valid: true }
  },

  /**
   * 重置表单
   */
  onReset() {
    wx.showModal({
      title: '确认重置',
      content: '确定要清空当前输入的内容吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            keyboardValue: '0',
            formData: {
              amount: '',
              category: '',
              categoryId: '',
              date: getCurrentDate(),
              time: getCurrentTime(),
              note: ''
            }
          })
          draftStorage.clearDraftBill()
          showSuccess('已重置')
        }
      }
    })
  },

  /**
   * 格式化显示金额
   */
  getDisplayAmount() {
    const amount = parseFloat(this.data.keyboardValue) || 0
    return formatAmount(amount)
  },

  /**
   * 获取当前分类列表
   */
  getCurrentCategories() {
    return this.data.billType === 'expense' 
      ? this.data.expenseCategories 
      : this.data.incomeCategories
  }
})